package com.automobile.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.automobile.domain.User;

public class LoginInterceptor implements HandlerInterceptor{

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		User user = (User) request.getSession().getAttribute("user");
		if(user!=null) {
			return true;
		}
		// 如果是ajax请求，请求头会有x-requested-with
	    String requestWith = request.getHeader("x-requested-with");
	    if (requestWith != null && requestWith.equalsIgnoreCase("XMLHttpRequest")){
	    	response.setHeader("SESSIONSTATUS", "TIMEOUT");
	    	response.setHeader("CONTEXTPATH", request.getContextPath()+"/login.html");
            // FORBIDDEN，forbidden。也就是禁止、403
	    	response.setStatus(HttpServletResponse.SC_FORBIDDEN);
	    } else {
	        response.sendRedirect("/WEB-INF/views/page/user/login.jsp");
	    }
	    return false;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle");
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		
	}
	
	
	
}
